<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-school"></i> 网站信息管理
                </el-breadcrumb-item>
                <el-breadcrumb-item>
                    <i class="el-icon-lx-pic"></i> 轮播图设置
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button
                        type="primary"
                        icon="el-icon-delete"
                        class="handle-del mr10"
                        @click="delAllSelection"
                >批量删除
                </el-button>
                <el-input placeholder="搜索标题"
                          v-model="search"
                          class="handle-input mr10"
                          clearable
                          @clear="getData(1,10)"
                          @keyup.enter.native="handleSearch"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            </div>
            <el-table
                    :data="rotationList"
                    border
                    class="table"
                    ref="multipleTable"
                    header-cell-class-name="table-header"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="rotationId" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="pictureTitle" label="标题" align="center"></el-table-column>
                <el-table-column label="轮播图片" align="center">
                    <template slot-scope="scope">
                        <el-image
                                class="table-td-img"
                                :src="scope.row.pictureUrl"
                                :preview-src-list="[scope.row.pictureUrl]"
                        ></el-image>
                    </template>
                </el-table-column>
                <el-table-column label="创建人" align="center">
                    <template slot-scope="scope">{{scope.row.createOne ? scope.row.createOne.nick : ''}}</template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间"></el-table-column>
                <el-table-column label="最后更新人">
                    <template slot-scope="scope">{{scope.row.updateOne ? scope.row.updateOne.nick : '暂无更新'}}</template>
                </el-table-column>
                <el-table-column label="最后更新时间">
                    <template slot-scope="scope">{{scope.row.updateTime ? scope.row.updateTime : '暂无更新'}}</template>
                </el-table-column>
                <el-table-column label="状态" align="center">
                    <template slot-scope="scope">
                        <el-tag
                                :type="scope.row.state=== 1 ?'success':'danger'"
                        >{{scope.row.state===1 ? '正在显示' : '已隐藏'}}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" align="center">
                    <template slot-scope="scope">
                        <el-button
                                type="text"
                                icon="el-icon-lx-attentionforbid"
                                v-show="scope.row.state===1"
                                style="color: #97a8be; margin-left: 10px"
                                @click="handleState(scope.$index, scope.row)"
                        >隐藏
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-lx-attention"
                                v-show="scope.row.state!==1"
                                style="color: #00a854"
                                @click="handleState(scope.$index, scope.row)"
                        >显示
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-edit"
                                @click="handleEdit(scope.$index, scope.row)"
                        >编辑
                        </el-button>
                        <el-button
                                type="text"
                                icon="el-icon-delete"
                                class="red"
                                @click="handleDelete(scope.$index, scope.row)"
                        >删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div class="addButt">
                <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
            </div>
            <div class="pagination">
                <el-pagination
                        background
                        layout="total, prev, pager, next"
                        :current-page="current"
                        :page-size="size"
                        :total="total"
                        @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="30%" center>
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="Id">
                    <el-input disabled v-model="form.rotationId"></el-input>
                </el-form-item>
                <el-form-item label="标题">
                    <el-input v-model="form.pictureTitle"></el-input>
                </el-form-item>
                <el-form-item label="图片">
                    <el-image :src="form.pictureUrl"
                         :preview-src-list="[form.pictureUrl]"
                         style="width: 200px">
                    </el-image>
                    <div class="crop-demo-btn">上传图片
                        <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage"/>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelEdit">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加弹出框 -->
        <el-dialog title="添加轮播图" :visible.sync="addVisible" width="30%" center @close="cancelEdit">
            <el-form ref="rotation" :model="rotation" label-width="70px">
                <el-form-item label="标题">
                    <el-input v-model="rotation.pictureTitle"></el-input>
                </el-form-item>
                <el-form-item label="图片">
                    <el-image :src="rotation.pictureUrl"
                              :preview-src-list="[rotation.pictureUrl]"
                              v-show="rotation.pictureUrl!==''"
                              style="width: 200px">
                    </el-image>
                    <div class="crop-demo-btn">上传图片
                        <input class="crop-input" type="file" name="image" accept="image/*" @change="setImage"/>
                    </div>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">添 加</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { getRequest, postRequest } from '../../api/index';
    import { getTime } from '../../utils/dateTimeUtil';

    export default {
        name: 'Rotation',
        data() {
            return {
                rotationList: [],
                multipleSelection: [],
                editVisible: false,
                addVisible: false,
                total: 0,
                size: 0,
                current: 1,
                form: {},
                idx: -1,
                baseUrl: 'http://localhost:8888',
                rotation: {
                    pictureTitle: '',
                    pictureUrl: ''
                },
                search: '',
                currentUserId: Number(sessionStorage.getItem('userId')),
                currentUserNick: sessionStorage.getItem('userNick'),
                file: {},
                oldTitle: '',
                oldUrl: ''
            };
        },
        inject: ['reload'],
        watch: {
            search(){
                if(this.search===''){
                    this.getData(1, 10);
                }
            }
        },
        created() {
            this.getData(1, 10);
        },
        beforeUpdate(){

        },
        methods: {
            getData(current, size) {
                const params = { current: current, size: size };
                getRequest('/getRotationList', params).then(resp => {
                    if (resp) {
                        this.total = resp.total;
                        this.current = resp.current;
                        this.size = resp.size;
                        resp.list.forEach(item=>{
                            item.pictureUrl=this.baseUrl+item.pictureUrl;
                        });
                        this.rotationList = resp.list;
                    } else {
                        console.log('获取轮播图列表失败');
                    }
                });
            },
            // 触发搜索按钮
            handleSearch() {
                if(this.search===''){
                    this.$message('搜索内容不能为空');
                    return false;
                }
                const params={
                    keyword: this.search,
                    current: 1,
                    size: 10
                };
                getRequest('/searchRotations', params).then(resp=>{
                    this.total = resp.total;
                    this.current = resp.current;
                    this.size = resp.size;
                    resp.list.forEach(item=>{
                        item.pictureUrl=this.baseUrl+item.pictureUrl;
                    });
                    this.rotationList = resp.list;
                });
            },
            // 删除操作
            handleDelete(index, row) {
                // 二次确认删除
                this.$confirm('确定要永久删除 "'+row.pictureTitle+'" 这个轮播图吗？', '提示', {
                    type: 'error'
                }).then(() => {
                    postRequest('/deleteRotation', {rotationId: row.rotationId}).then(resp=>{
                        if(resp==='success'){
                            this.$message.success('删除成功');
                            this.rotationList.splice(index, 1);
                        }
                    })
                });
            },
            // 多选操作
            handleSelectionChange(val) {
                this.multipleSelection = val;
            },
            delAllSelection() {
                const length = this.multipleSelection.length;
                if(length===0){
                    this.$message("请选择要删除的轮播图！");
                    return false;
                }
                const deleteList = [];
                this.multipleSelection.forEach(item=>{
                    deleteList.push(item.rotationId);
                });
                this.$confirm('确定要永久删除这 '+length+' 个轮播图吗？', '警告',{type: 'warning'}).then(()=>{
                    postRequest('/deleteRotations', {deleteList: deleteList}).then(resp=>{
                        if(resp==='success'){
                            this.$message.error(`已删除 ${length} 个轮播图！`);
                            this.multipleSelection = [];
                            this.reload();
                        }
                    })
                })
            },
            // 编辑操作
            handleEdit(index, row) {
                this.idx = index;
                this.form = row;
                this.oldTitle=row.pictureTitle;
                this.oldUrl=row.pictureUrl;
                this.editVisible = true;
            },
            cancelEdit(){
                this.form.pictureTitle=this.oldTitle;
                this.form.pictureUrl=this.oldUrl;
                this.editVisible=false;
                this.form={};
                this.file=null;
            },
            // 保存编辑
            saveEdit() {
                if(this.form.pictureTitle===''){
                    this.$message.error('标题不能为空');
                    return false;
                }
                if(this.form.pictureTitle === this.oldTitle
                    &&
                    this.form.pictureUrl===this.oldUrl){
                    this.$message('未作任何修改');
                    return false;
                }
                const time=new Date();
                this.form.updateOne={nick: this.currentUserNick};
                this.form.updateTime=getTime(time);
                let formData=new FormData();
                formData.append('img',this.file);
                formData.append('currentUserId', this.currentUserId);
                formData.append('rotationId', this.form.rotationId);
                formData.append('imgTitle', this.form.pictureTitle);
                formData.append('updateTime', time.getTime()+'');
                this.$axios({
                    method: 'post',
                    url: '/api/modifyRotation',
                    data: formData
                }).then(resp=>{
                    if(resp.data==='success'){
                        this.$message.success(`修改第 ${this.idx + 1} 行成功`);
                    }
                });
                this.editVisible = false;
                this.$set(this.rotationList, this.idx, this.form);
                this.rotation.pictureUrl='';
                this.form={};
            },
            handleAdd(){
                this.rotation.pictureUrl='';
                this.rotation.pictureTitle='';
                this.addVisible=true;
            },
            saveAdd() {
                if(this.rotation.pictureTitle===''){
                    this.$message.error('图片标题不能为空');
                    return false;
                }
                this.addVisible=false;
                let formData=new FormData();
                formData.append('img',this.file);
                formData.append('currentUserId', this.currentUserId);
                formData.append('imgTitle', this.rotation.pictureTitle);
                this.$axios({
                    method: 'post',
                    url: '/api/addRotation',
                    data: formData
                }).then(resp=>{
                    if(resp.data==='success'){
                        this.$message.success('添加成功！');
                    }
                });
                this.reload();
            },

            //显示和隐藏
            handleState(index, row){
                this.idx=index;
                this.form=row;
                if(this.form.state===1){
                    this.form.state=0;
                }else{
                    this.form.state=1;
                }
                this.form.updateOne={nick: this.currentUserNick};
                const date=new Date();
                this.form.updateTime=getTime(date);
                const params={
                    rotationId: this.form.rotationId,
                    state: this.form.state,
                    currentUserId: this.currentUserId,
                    updateTime: date.getTime()
                };
                postRequest('/changeState', params).then(resp=>{
                    if(resp==='success'){
                        this.form.state===1 ?
                            this.$message.success('轮播图已显示！')
                            :
                            this.$message('轮播图已隐藏！');
                    }else{
                        this.$message.error('操作失败！');
                    }
                });
                this.$set(this.rotationList, this.idx, this.form);
            },

            // 分页导航
            handlePageChange(val) {
                this.getData(val, this.size);
            },
            setImage(e){
                const file = e.target.files[0];
                this.file=file;
                if (!file.type.includes('image/')) {
                    this.$message.error('请选择图片文件');
                    return;
                }
                const reader = new FileReader();
                reader.onload = (event) => {
                    this.rotation.pictureUrl = event.target.result;
                    if(this.form.pictureUrl) this.form.pictureUrl=this.rotation.pictureUrl;
                    e.target.value='';
                };
                reader.readAsDataURL(file);
            }
        }
    };
</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-img {
        display: block;
        margin: auto;
    }
    .addButt{
        margin-top: 15px;
    }
    .crop-demo-btn{
        position: relative;
        width: 100px;
        height: 40px;
        line-height: 40px;
        padding: 0 20px;
        margin-left: 30px;
        background-color: #409eff;
        color: #fff;
        font-size: 14px;
        border-radius: 4px;
        box-sizing: border-box;
    }
    .crop-input{
        position: absolute;
        width: 100px;
        height: 40px;
        left: 0;
        top: 0;
        opacity: 0;
        cursor: pointer;
    }
</style>
